package controllers

import (
	"github.com/astaxie/beego"
	"hw_admin/models"
	"hw_admin/enums"
	"strconv"
)

type BaseController struct {
	beego.Controller
	controllerName string             //当前控制名称
	actionName     string             //当前action名称
	cur 	models.AdminUser		//当前用户
	models 	[]models.VModule		//当前菜单
}



//执行方法之前执行
func (this *BaseController) Prepare()  {
	//调用GetControllerAndAction获取
	this.controllerName,this.actionName = this.GetControllerAndAction()
	this.adapterUserInfo()
	//获取左侧菜单为nil时跳转到登陆
	//if this.cur.Id == 0 {
	//	this.Redirect("/admin",302)
	//}
	//layout模板
	//this.Layout = "index.html"
}

//@param count 总条数
//@param pageNo 当前页
//@param pageSize 页码大小
//@return 分页html
func (this *BaseController) GetPage(count, pageNo, pageSize int) string {
	if count == 0 {
		return "<div> 无数据 </div>"
	}
	totalPage := count/pageSize + 1
	return createHtml(totalPage,pageNo)
}

type DD interface {
	
} 

func createHtml(totalPage,pageNo int ) string  {
	if totalPage == 1 {
		return "<div><span class='current'>1</span></div>"
	}
	pageHtml := "<div>"
	if pageNo != 1 {
		pageHtml += "<a class='prev' href=''>&lt;&lt;</a>"
	}
	for i := 1 ;i <= totalPage ; i ++ {
		if pageNo == i {
			pageHtml += "<span class='current'>"+ strconv.Itoa(i) +"</span>"
		}else {
			pageHtml += "<a class='num' href=''>"+ strconv.Itoa(i) +"</a>"
		}
	}
	if totalPage > pageNo {
		pageHtml += "<a class='next' href=''>&gt;&gt;</a>"
	}
	pageHtml += "</div>"
	return pageHtml
}

//从session里取用户信息
func (this *BaseController) adapterUserInfo() {
	a := this.GetSession("adminuser")

	if a != nil {
		this.cur = a.(models.AdminUser)
		this.Data["adminuser"] = a
	}
}

//从session中获取菜单信息
func (this *BaseController) adapterModels ()  {
	m := this.GetSession("models")
	if m != nil {
		this.models = m.([]models.VModule)
		this.Data["models"] = m
	}
}

//返回json对象
func (this *BaseController) jsonResult(code enums.JsonResultCode, msg string, obj interface{}) {
	r := &models.JsonResult{code, msg, obj}
	this.Data["json"] = r
	this.ServeJSON()
	this.StopRun()
}
